import React, { useContext, useEffect, useState } from 'react';
import {
    Alert,
    DeviceEventEmitter,
    ImageBackground,
    RefreshControl,
    TextInput,
    TouchableOpacity,
    View
} from 'react-native';
import { Icon, Image, ListItem, Text } from 'react-native-elements';
import LocaleContext from '../libs/locale';
import WalletContext from '../libs/wallet';
import AsyncStorage from '@react-native-async-storage/async-storage';

import susdtlogo from '../assets/susdt.png';
import sETHlogo from '../assets/1.png';
import otherTokenLogo from '../assets/hotTokenLogo.png';

import {constansts} from "./../libs/constansts";
import { ScrollView } from 'react-native-gesture-handler';
import {getHotTokens, getTokenName} from '../libs/nodes';
import pool_find from "../assets/Pool/pool_find.png";


const GetTokens = ({navigation,route}:any) =>{
    const locale = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);
    const [refresh, setRefresh] = useState(true);
    const [seachTxt,setSeachTxt] = useState('');
    const [tokenList,setTokenList] = useState([]);
    const [tokenAddList,setTokenAddList] = useState(JSON.stringify(constansts.addTokens));
    const [showSearch,setShowSearch] = useState(false);

    const Anti_shake = (value:string) =>{
        console.log(`第一个t=`+constansts.t)
        if(constansts.t!==null)
        {
            clearTimeout(constansts.t);
            console.log(`清理后t=`+constansts.t)
        }
        constansts.t=setTimeout(()=>{searchEnding(value.trim())},500)//2行代码简单防抖
        console.log(`设置后t=`+constansts.t)
        setSeachTxt(value.trim());
    }

    useEffect(() => {
        const work=async () => {
            if(!refresh)
            {
                return ;
            }
            console.log("3-1")
            setRefresh(false);
            const ht=await getHotTokens();
            var hotTokens=JSON.parse(JSON.stringify(ht));
            if(hotTokens.res_info=="OK")
            {
                constansts.HotTokens=hotTokens.tokens;
                setTokenList(hotTokens.tokens);
                setShowSearch(false);
                console.log(5)
            }
            console.log(4)
        }
        work();

    },[wallet,refresh]);

    const searchEnding = async (value:string)=>{
        try {
            if(value=="")
            {
                return ;
            }
            var tokenName;
            try{
                tokenName = await getTokenName(value);
            }catch (e) {
                setTokenList([]);
                setShowSearch(false);
                return ;
            }

            console.log("tokenName="+tokenName);
            // var searchToken = {address:seachTxt,uri:"",desc:tokenName};
            var searchToken = [{address:value,url:"",desc:tokenName}];
            for(var i=0;i<constansts.HotTokens.length;i++)
            {
                if((constansts.HotTokens as any)[i].address==searchToken[0].address)
                {
                    searchToken[0].url=(constansts.HotTokens as any)[i].url;
                }
            }
            setTokenList((searchToken as any));
            setShowSearch(true);
            // setSeachTxt('');
        } catch (e) {
            console.log('searchEnding==>', e);
            setSeachTxt('');
            Alert.alert("",locale?._("Token.tokenNonExit"),[{text: (locale?._('Assets.send.OK') as any)}]);
        }
    };

    const addTs = async (tx:any)=>{
        console.log("1")

        // console.log((JSON.stringify(constansts.tokens).indexOf(tx.address)));
        // console.log((JSON.stringify(constansts.NotShowTokens).indexOf(tx.address)));

        if((JSON.stringify(constansts.tokens).indexOf(tx.address)<0))
        {
            //添加
            if((JSON.stringify(constansts.addTokens).indexOf(tx.address)<0))
            (constansts.addTokens as any).push(tx);
            setTokenAddList(JSON.stringify(constansts.addTokens));
            console.log("tokenAddList.string = "+tokenAddList)
            // (constansts.tokens as any).push(tx);
            // console.log("显示的："+JSON.stringify(constansts.addTokens));
            await AsyncStorage.setItem('@addTokens',JSON.stringify(constansts.addTokens as any));
        }
        else{
            //删除

            // for(var i=0;i<(constansts.tokens).length;i++)
            // {
            //     if((constansts.tokens[i] as any).address==tx.address)
            //     {
            //         (constansts.tokens as any).splice(i,1);
            //         break;
            //     }
            // }

            for(var i=0;i<(constansts.addTokens).length;i++)
            {
                if((constansts.addTokens[i] as any).address==tx.address)
                {
                    (constansts.addTokens as any).splice(i,1);
                    break;
                }
            }
            setTokenAddList(JSON.stringify(constansts.addTokens));
            console.log("tokenAddList.string = "+tokenAddList)
            await AsyncStorage.setItem('@addTokens',JSON.stringify(constansts.addTokens as any));
         }
         // console.log("constansts.tokens:"+JSON.stringify(constansts.tokens));
        console.log("2")
        // setRefresh(true);

    }
    return (
        <View>
            <View style={{flexDirection:"row",justifyContent:"center"}}>
                <View style={{justifyContent:"center",height:40,width:"90%",flexDirection:"row",backgroundColor:"#E7E7E8",borderRadius:20,marginTop:10}}>
                    <ImageBackground
                        source={pool_find}
                        style={{ width: 20, height:20, marginLeft:25,paddingRight:35,borderRightWidth:0.2,alignSelf:'center' }} />
                    <TextInput
                        underlineColorAndroid={'transparent'}
                        placeholder= {locale?._('Token.tokenSearch')}
                        defaultValue={seachTxt}
                        // selectTextOnFocus={true}
                        // pointerEvents={'auto'}
                        // enablesReturnKeyAutomatically={false}
                        // onselectstart="return false;" onpaste="return false;" type="text"
                        onChangeText={
                            (value) => {
                                Anti_shake(value);
                            }
                        }
                        // onEndEditing={()=>searchEnding(seachTxt)}
                        style={{
                            flex:1,
                            paddingRight:20
                        }
                        }
                    />
                </View>
                {/*<Text style={{marginLeft:"2%",alignSelf:"center",fontWeight:"bold"}}>取消</Text>*/}
            </View>
            {
                !showSearch?<Text style={{marginTop:15,marginLeft:20,fontWeight:"bold",fontSize:18}}>{locale?._('Token.hotTokens')}</Text>:null

            }


            <ScrollView refreshControl={
            <RefreshControl refreshing={false} onRefresh={() => setRefresh(true)} collapsable={true} />} >
            <View >
                {
                    tokenList.length
                    ?
                    tokenList.map((tx: any,index:any) => (
                    <ListItem bottomDivider onPress={async ()=>{
                        await addTs(tx);
                    }} activeOpacity={1} key={index}>
                        {
                           tx.address==constansts.contractAddressImage.sETH?
                           <ImageBackground source={sETHlogo} style={{ width: 38, height: 38 }} />
                           :
                           (
                                tx.address==constansts.contractAddressImage.sUSDT?
                                <ImageBackground source={susdtlogo} style={{ width: 38, height: 38 }} />
                                :
                                (
                                    tx.url==""?
                                    <ImageBackground source={otherTokenLogo} style={{ width: 38, height: 38 }} />
                                    :
                                    <ImageBackground source={{uri:tx.url}} style={{ width: 38, height: 38 }} />
                                )
                           )
                        }
                        <ListItem.Content>
                        <ListItem.Title style={{fontSize:13}}>{tx.desc}</ListItem.Title>
                        <ListItem.Subtitle style={{fontSize:11}}>{tx.address.slice(0,9)+"..."+tx.address.slice(-10)}</ListItem.Subtitle>
                        </ListItem.Content>
                        {
                            (tokenAddList).indexOf(tx.address)!==-1?
                            <Icon type='feather' name='minus-circle' color='#7259E0FF' size={24}  />
                            :
                            <Icon type='feather' name='plus-circle' color='#7259E0FF' size={24} />
                        }
                    </ListItem>
                    ))
                    :
                    <View style={{ flex: 1, justifyContent: 'center' }}>
                    <Text style={{
                        marginTop: '100%',
                        fontSize: 20,
                        textAlign: 'center',
                        color: 'grey'
                    }}>{locale?._('noContent')}</Text>
                    </View>
                }

            </View>
            </ScrollView>
        </View>
    );

};
export default GetTokens;
